06. Insert Points
Header Text
Insert Points
Starter Code Walkthrough
ND312 C1 L3 A29 Insert Points - Concept [LB]
Insert Points
The previous concept showed how points are inserted into the tree. How about doing this in C++? Implementing a recursive helper function to insert points can be a very nice way to update Nodes. The basic idea is that the tree is traversed until the Node it arrives at is NULL, in which case a new Node is created and replaces the NULL Node. For assigning a Node, one way is to use a double pointer. You could pass in a pointer to the node, starting at root, and then when you want to replace a node you can dereference the double pointer and assign it to the newly created Node. Another way of achieving this is by using a pointer reference as well. For references, check out the code below for doing insertion in C++ but with a binary tree. The insertion for a KD-Tree will be very similar to this.
Example of Insertion for Binary Tree
Double Pointer
void insert(BinaryTreeNode **node, int data)
{
if(*node == NULL)
{
*node = getNewNode(data);
}
else if(data < (*node)->data)
{
insert(&(*node)->left, data);
}
else
{
insert(&(*node)->right, data);
}
}
Pointer Reference
void insert(BinaryTreeNode *&node, int data)
{
if(node == NULL)
{
node = getNewNode(data);
}
else if(data < node->data)
{
insert(node->left, data);
}
else
{
insert(node->right, data);
}
}
Instructions
Check out the quiz and try getting the resulting image from the previous concept, visually showing how each point is separating the x/y regions.
-
In
src/quiz/cluster/kdtree.h
fill in theinsert
function.
Compile/Run
-
In
src/quiz/cluster
,mkdir build
-
cd build
-
cmake ..
-
make
-
./quizCluster
Workspace
This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity , so you may be able to download them there.
Workspace Information:
- Default file path:
- Workspace type: react
- Opened files (when workspace is loaded): n/a
Solution
ND313 C1 L3 A33 Insert Points - Solution